import React, { useState, useEffect, useRef } from 'react';
import { connect } from 'react-redux';
import { View, Text, Image, ScrollView } from '@tarojs/components';
import { debounce } from '@/utils/helper';
import Taro from '@tarojs/taro';
import pBack from '@/images/common/back.svg';
import pZdfmj from '@/mainSubPack/images/superCostEffective/zdfmj.png';
import pDitu from '@/mainSubPack/images/superCostEffective/ditu.png';
import pDingwei from '@/mainSubPack/images/superCostEffective/dingwei.png';

import './index.scss';

const bar = {
  title: '超划算',
  back: true,
};
const background = {
  backgroundColor: '#ffdc26',
  contentWidth: 60,
};

const pageSize = 10;

const goBackHomePage = () => {
  let url = '/pages/mainPages/homePage/homePage';
  Taro.navigateBack({
    url,
  });
};

const Rad = (d) => {
  return (d * Math.PI) / 180.0;
};
const getDistance = (lat1, lng1, lat2, lng2) => {
  if (lat2.length == 0 || lng2.length == 0) {
    return '--';
  }
  let radLat1 = Rad(lat1);
  let radLat2 = Rad(lat2);
  let a = radLat1 - radLat2;
  let b = Rad(lng1) - Rad(lng2);
  let s =
    2 *
    Math.asin(
      Math.sqrt(
        Math.pow(Math.sin(a / 2), 2) +
          Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2),
      ),
    );
  s = s * 6378.137;
  s = Math.round(s * 10000) / 10000;
  s = s.toFixed(1) + 'km';
  return s;
};

const SuperCostEffectivePage = ({ dispatch, vemInfoList, vemPages }) => {
  const [vendingMachineList, setVendingMachineList] = useState([]);
  const [page, setPage] = useState(1);
  const [curLocation, setCurLocation] = useState(null);
  const flags = useRef({ isLoading: false, finished: false });

  const showNextPageVem = debounce(() => {
    if (flags.current.finished) return;
    if (!flags.current.isLoading) {
      flags.current.isLoading = true;
      let nextPage = page + 1;
      if (nextPage >= vemPages.totalPage) {
        flags.current.finished = true;
      }
      setPage(nextPage);
    }
  }, 1200);

  const showMap = (latitude, longitude) => {
    Taro.openLocation({
      latitude: Number(latitude),
      longitude: Number(longitude),
      scale: 15,
    });
  };

  useEffect(() => {
    Taro.getLocation({
      type: 'gcj02',
      isHighAccuracy: true,
      success: (res) => {
        const { latitude, longitude, speed, accuracy } = res;
        setCurLocation({ latitude, longitude, speed, accuracy });
      },
    });
  }, []);

  useEffect(() => {
    dispatch({
      type: 'otherApi/selectDevicePage',
      payload: { page, pageSize },
    });
  }, [page]);

  useEffect(() => {
    flags.current.isLoading = false;
    let vemList = Object.assign([], vendingMachineList, vemInfoList);
    if (Object.keys(vemPages).length > 0 && vemList.length >= vemPages.totalCount) {
      flags.current.finished = true;
    }
    if (vemList.length > 0 && curLocation) {
      vemInfoList.map((vem) => {
        if (vem.hasOwnProperty('distance') == false) {
          vem.distance = getDistance(
            curLocation.latitude,
            curLocation.longitude,
            vem.latitude,
            vem.longitude,
          );
        }
      });
    }
    setVendingMachineList(vemList);
  }, [vemInfoList, curLocation]);

  return (
    <View className="totalPage_superCostEffective">
      {background ? (
        background.src ? (
          <View
            className="topBackground"
            style={{
              height: background.contentWidth + Taro.$statusBarHeight + Taro.$titleHeight + 'px',
            }}
          >
            <Image className="topBackgroundImg" src={background.src}></Image>
          </View>
        ) : (
          <View
            className="topBackground"
            style={{
              background: background.backgroundColor,
              height: background.contentWidth + Taro.$statusBarHeight + Taro.$titleHeight + 'px',
            }}
          ></View>
        )
      ) : (
        <View className="topBackground"></View>
      )}
      <View className="fontPage">
        {!Taro.$isH5 && (
          <View
            className="topBar"
            style={{
              height: Taro.$titleHeight + 'px',
              top: Taro.$statusBarHeight + 'px',
            }}
          >
            {bar && (
              <>
                {bar.back ? (
                  <Image className="backIcon" src={pBack} onclick={goBackHomePage} />
                ) : (
                  <View className="backIcon"></View>
                )}
                <Text className="title">{bar.title}</Text>
                <View className="backIcon"></View>
              </>
            )}
          </View>
        )}

        <ScrollView
          className="contentPage"
          scrollY
          lowerThreshold={240}
          style={{
            marginTop: Taro.$titleHeight + Taro.$statusBarHeight + 'px',
            height: 'calc(100% - ' + Taro.$titleHeight + 'px - ' + Taro.$statusBarHeight + 'px)',
          }}
          onScrollToLower={showNextPageVem}
        >
          <View className="scepContent">
            <Image className="machineTop" src={pZdfmj} />
            <View className="machineList">
              {vendingMachineList.length > 0 ? (
                vendingMachineList.map((machine) => (
                  <View className="machineInfo" key={'machine_' + machine.id}>
                    <View className="left">
                      <Image className="dwIcon" src={pDingwei} />
                    </View>
                    <View className="center">
                      <View className="base">
                        <Text className="name">{machine.orgName}</Text>
                        <View className="other">
                          <Text className="time">24小时营业</Text>
                          <Text className="num">{'在售商品：' + machine.onSaleNum + '件'}</Text>
                        </View>
                      </View>
                      <Text className="addr">{'地址：' + machine.address}</Text>
                    </View>
                    <View
                      className="right"
                      onClick={() => showMap(machine.latitude, machine.longitude)}
                    >
                      <Image className="dtIcon" src={pDitu} />
                      <Text className="distance">{machine.distance || '--'}</Text>
                    </View>
                  </View>
                ))
              ) : (
                <View className="machineInfo">
                  <Text className="noVem">暂无售货机</Text>
                </View>
              )}
            </View>
          </View>
        </ScrollView>
      </View>
    </View>
  );
};

export default connect(({ otherApi }) => ({
  vemInfoList: otherApi.vemInfoList,
  vemPages: otherApi.vemPages,
}))(SuperCostEffectivePage);
